﻿using Inaction.Core;
using Inaction.Rule;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Inaction.Extensions.Serialization
{
    public class BinarySerializer : BaseSerializer
    {

        public override byte[] Serialize(object obj)
        {
            var serializer = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            serializer.Serialize(ms, obj);
            return ms.ToArray();
        }
        public override string SerializeToString(object obj)
        {
            return System.Text.Encoding.Unicode.GetString(Serialize(obj));
        }
        public override T Deserialize<T>(byte[] data)
        {
            var serializer = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(data);
            return (T)serializer.Deserialize(ms);
        }

        public override object Deserialize(Type type, byte[] data)
        {
            var serializer = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(data);
            return serializer.Deserialize(ms);
        }

        public override SerializeType SerializeType
        {
            get { return SerializeType.Binary; }
        }
    }
}
